//
//  Copyright 2013  Thomas Darmengeat
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

//TODO : Organiser le code pour passer par des objets avec configuration d'options
//TODO : Créer la boucle de temps pour tester à intervalle régulier
//TODO : Créer la possibilite de le lancer au demarrage de windows
//TODO : Prévoir la possibilité d'avoir d'autre fournisseur DNS dynamique
namespace OvhDynHost
{
	class MainClass
	{
		/// <summary>
		/// The entry point of the program, where the program control starts and ends.
		/// </summary>
		/// <param name="args">The command-line arguments.</param>
		public static int Main (string[] args)
		{
			//// URL exemple du programme ==> http://".$DynDNSUsername.":".$DynDNSPassword."@".$DynDNSServiceProvider."/nic/update?system=dyndns&hostname=".$DynDNSHostname."&myip=".$CurrentPublicIP."&wildcard=no"
			//TODO : Passer par une url avec encodage des credential en Base64
			string regexp = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
			string urlIpCheck = @"http://checkip.dyndns.com/";
			string fileIp = System.Environment.CurrentDirectory + "\\ip.find", fileLog = System.Environment.CurrentDirectory + "\\ip.log";
			string ip = string.Empty, oldIp = string.Empty, uri = string.Empty, doing = string.Empty, log = string.Empty;
			Regex ipFilter = new Regex (regexp);
			WebClient wc = new WebClient ();
			FileStream ipsw = null;
			StreamWriter logsw = null;
			UnicodeEncoding uniEncoding = new UnicodeEncoding ();

			try {

				if (File.Exists (fileIp)) {
					byte[] ipData = File.ReadAllBytes (fileIp);
					oldIp = uniEncoding.GetString (ipData, 0, ipData.Length);
				}

				ipsw = File.Open (fileIp, FileMode.OpenOrCreate);
				//logsw = File.Open (fileLog, FileMode.OpenOrCreate);
				logsw = File.AppendText (fileLog);
				ip = wc.DownloadString (urlIpCheck);
				ip = ipFilter.Match (ip).Value;
				if (!oldIp.Equals (ip)) {
					if (logsw != null) {
						logsw.WriteLine (string.Format (@"{0} => Ip find: {1}", DateTime.Now, ip));
						logsw.Flush ();
					}

					uri = string.Format (@"http://{0}:{1}@{2}/nic/update?system=dyndns&hostname={3}&myip={4}&wildcard=no", 
						ConfigurationManager.AppSettings ["login"].ToString (), 
						ConfigurationManager.AppSettings ["mdp"].ToString (), 
						ConfigurationManager.AppSettings ["url"].ToString (), 
						ConfigurationManager.AppSettings ["host"].ToString (), 
						ip);
					doing = wc.DownloadString (uri);
					Console.WriteLine (doing);
					log = string.Format (@"{0} ==> {1}", DateTime.Now, doing);
				} else {
					log = string.Format (@"{0} ==> Nothing to do ...", DateTime.Now);
				}

				if (logsw != null) {
					logsw.WriteLine (log);
				}

			} catch (Exception e) {
				ip = string.Empty;//En cas d'erreur l'ip est mmis à blanc pour etre réinitialisé automatiquement au prochain lancement
				if (logsw != null) {
					logsw.WriteLine (e.Message);
				} else {
					System.Diagnostics.Trace.WriteLine (e.Message);
					Console.Out.WriteLine (e.Message);
				}
			}
			if (logsw != null) {
				logsw.Flush ();
				logsw.Close ();
			}

			if (ipsw != null) {
				ipsw.Write (uniEncoding.GetBytes (ip), 0, uniEncoding.GetByteCount (ip));
				ipsw.Flush ();
				ipsw.Close ();
			}

			return 0;
		}
	}
}